<?php

// 公共助手函数
use think\Db;
use Symfony\Component\VarExporter\VarExporter;
require_once "wxpay/lib/WxPay.Api.php";
require_once "wxpay/example/WxPay.Config.php";
require_once "wxpay/example/WxPay.JsApiPay.php";

 function refund_order($out_trade_no,$total_fee,$refund_fee){
    $input = new \WxPayRefund();
    $input->SetOut_trade_no($out_trade_no);
    $input->SetTotal_fee($total_fee);
    $input->SetRefund_fee($refund_fee);
    $config = new \WxPayConfig();
    $input->SetOut_refund_no("sdkphp".date("YmdHis"));
    $input->SetOp_user_id($config->GetMerchantId());
    $result = \WxPayApi::refund($config, $input);
    return $result;
}
/**
 * 去除Html所有标签、空格以及空白，并截取字符串（包括中文）
 * @param  string $string 字符串
 * @param  number $sublength 字符串长度
 * @param  string $encoding 编码方式
 * @param  string $ellipsis 省略号
 */
if (!function_exists('StringToText')){


    function StringToText($string, $sublength = 20, $encoding = 'utf-8', $ellipsis = '…'){
        $string = trim($string); //清除字符串两边的空格
        $string = strip_tags($string,""); //利用php自带的函数清除html格式
        $string = preg_replace("/\t/","",$string); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
        $string = preg_replace("/&nbsp;/","",$string); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
        $string = preg_replace("/\r\n/","",$string);
        $string = preg_replace("/\r/","",$string);
        $string = preg_replace("/\n/","",$string);
        $string = preg_replace("/ /","",$string);
        $string = preg_replace("/  /","",$string);  //匹配html中的空格
        if(mb_strlen(trim($string),'utf-8') < $sublength){
            return trim($string).$ellipsis;
        }else{
            return mb_strcut(trim($string),0,$sublength,$encoding).$ellipsis;
        }
    }
}
function getQuerystr($url,$key){
    $res = '';
    $a = strpos($url,'?');
    if($a!==false){
        $str = substr($url,$a+1);
        $arr = explode('&',$str);
        foreach($arr as $k=>$v){
            $tmp = explode('=',$v);
            if(!empty($tmp[0]) && !empty($tmp[1])){
                $barr[$tmp[0]] = $tmp[1];
            }
        }
    }
    if(!empty($barr[$key])){
        $res = $barr[$key];
    }
    return $res;
}
//生成订单号
if (!function_exists('getOrderSn')) {
    function getOrderSn($type = '')
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $num = round(0,9);
        $orderSn = $type.$yCode[$num] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5);
        $count = Db::name('order')->where('order_sn',$orderSn)->count();
        if($count){
            getOrderSn($type);
        }
        return $orderSn;
    }
}
/**
 * 去除Html所有标签、空格以及空白，并截取字符串（包括中文）
 * @param  string $string 字符串
 * @param  number $sublength 字符串长度
 * @param  string $encoding 编码方式
 * @param  string $ellipsis 省略号
 */
if (!function_exists('StringToText')){


    function StringToText($string, $sublength = 20, $encoding = 'utf-8', $ellipsis = '…'){
        $string = trim($string); //清除字符串两边的空格
        $string = strip_tags($string,""); //利用php自带的函数清除html格式
        $string = preg_replace("/\t/","",$string); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
        $string = preg_replace("/&nbsp;/","",$string); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
        $string = preg_replace("/\r\n/","",$string);
        $string = preg_replace("/\r/","",$string);
        $string = preg_replace("/\n/","",$string);
        $string = preg_replace("/ /","",$string);
        $string = preg_replace("/  /","",$string);  //匹配html中的空格
        if(mb_strlen(trim($string),'utf-8') < $sublength){
            return trim($string).$ellipsis;
        }else{
            return mb_strcut(trim($string),0,$sublength,$encoding).$ellipsis;
        }
    }
}
if (!function_exists('getConfig')) {
    function getConfig($url = ""){
        $array = [];
        $array['debug'] = true;
        $array['appId'] = 'wx1b231da6c9445019';
        //生成签名的时间戳
        $time = time();
        $array['timestamp'] = $time;
        //签名使用的随机字符串
        $nonceStr = nonceStr();
        $array['nonceStr'] = $nonceStr;
        $array['signature'] = signature($time,$url,$nonceStr);
        //设置需要使用的js接口
        //返回配置信息
        return $array;
    }
}
//生成随机字符串
function nonceStr(){
    //定义一个字符串
    $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    //当前的时间戳
    $time = time();
    //从该字符串中获取随机字符串
    $chars = $chars.$time;
    //打乱字符串
    $chars = str_shuffle($chars);
    return substr($chars,0,16);
}

function signature($time,$url,$nonceStr){
    //拼接字符串
    $string = 'jsapi_ticket='.getJsapiTicket().'&noncestr='.$nonceStr.'&timestamp='.$time.'&url='.$url;
    //生成签名
    $string = sha1($string);
    return $string;
}
function getJsapiTicket(){
    //我们将jsapi_ticket全局缓存在文件中,每次获取的时候,先判断是否过期,如果过期重新获取再全局缓存
    //我们缓存的在文件中的数据，包括jsapi_ticket和该jsapi_ticket的过期时间戳.
    //获取缓存的access_token
    if(is_file('jsapi_ticket.txt')){
        $jsapi_ticket_file = file_get_contents("jsapi_ticket.txt");
        $jsapi_ticket_data = json_decode($jsapi_ticket_file,true);
    }else{
        $jsapi_ticket_data = null;
    }

    //判断缓存的access_token是否存在和过期，如果不存在和过期则重新获取.
    if($jsapi_ticket_data !== null && $jsapi_ticket_data['ticket'] && $jsapi_ticket_data['expires_in'] > time()){

        return $jsapi_ticket_data['ticket'];

    }else{
        //重新获取jsapi_ticket,并全局缓存
        /*$curl = curl_init();*/
        $token = getAccessToken();
        //getAccessToken()函数获取js-sdk需要的access_token,我在上一篇博客中写到过.
        /*curl_setopt($curl,CURLOPT_URL,'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$token.'&type=jsapi');

        curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);*/
        $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$token.'&type=jsapi');
        //获取jsapi_ticket
        $data = json_decode($res,true);
        if($data != null && $data['ticket']){
            //设置jsapi_ticket的过期时间,有效期是7200s
            $data['expires_in'] = 7000 + time();

            //将jsapi_ticket全局缓存，快速缓存到文件中.
            file_put_contents("jsapi_ticket.txt",json_encode($data));
            // S('jsapi_ticket',json_encode($data));

            //返回jsapi_ticket
            return $data['ticket'];

        }else{
            exit('微信获取jsapi_ticket失败');
        }
    }
}


function getAccessToken(){
    //我们将access_token全局缓存在文件中,每次获取的时候,先判断是否过期,如果过期重新获取再全局缓存
    //我们缓存的在文件中的数据，包括access_token和该access_token的过期时间戳.
    //获取缓存的access_token
    if(is_file("access_token.txt")){
        $access_tokenfile = file_get_contents("access_token.txt");
        $access_token_data = json_decode($access_tokenfile,true);
    }else{
        $access_token_data = null;
    }


    //判断缓存的access_token是否存在和过期，如果不存在和过期则重新获取.
    if($access_token_data !== null && $access_token_data['access_token'] && $access_token_data['expires_in'] > time()){

        return $access_token_data['access_token'];

    }else{
        //重新获取access_token,并全局缓存
        /*$curl = curl_init();

        curl_setopt($curl,CURLOPT_URL,'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='
            .C('appID').'&secret='.C('appSecret'));

        curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);*/
        $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='
            .'wx1b231da6c9445019'.'&secret='.'cd8afaca3c03d30b149d2415ca5759fb');
        //获取access_token
        $data = json_decode($res,true);
        if($data != null && $data['access_token']){
            //设置access_token的过期时间,有效期是7200s
            $data['expires_in'] = time() + 7000;

            //将access_token全局缓存，快速缓存到文件中.
            file_put_contents("access_token.txt",json_encode($data));
            //返回access_token
            return $data['access_token'];

        }else{
            exit('微信获取access_token失败');
        }
    }
}
function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}
if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}
/*
*  富文本图片增加域名
*  $content    文本内容
*  $suffix     域名
* */
if(!function_exists('get_img_thumb_url')){

    function get_img_thumb_url($content = "", $suffix = "")
    {
        $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
        /*$pregRule1 = "/<[a|A].*?href=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";*/
        $content = preg_replace($pregRule, '<img src="' . $suffix . '${1}" >', $content);
        //$content = preg_replace($pregRule1, '<a href="' . $suffix . '${1}" ">', $content);
        return $content;
    }
}
if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var 数组
     * @return string
     */
    function var_export_short($var)
    {
        return VarExporter::export($var);
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                header('HTTP/1.1 403 Forbidden');
                exit;
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                exit;
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}
